/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
			name : 'workLayer',
			title : 'workLayer',
			type : 'LineEdit',
			property : {tool_tip : '工作层inner 或者 out'}
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 调整阻抗线 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) { PAR = $.par } else if ($.hasOwnProperty('script_parameter')){ PAR = JSON.parse($.script_parameter); }
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({ table: "pdm_aimdfm_task", data: { current_process_title: $.process_title }, where: { id: $.task_id } });
	}
}
var Status = 'ok';
var resultData = [];
var par = PAR;
var default_par = {
	step: "unit.+",
	step2:"unit",
	auto_save: "No",
	workLayer:"all",
	units:"mm"
}
for(var key in default_par){ if (!par.hasOwnProperty(key) || par[key] == ""){ par[key] = default_par[key] }}
var job = Job;
try {
	if(_.isEmpty(job)){throw "参数job不存在"} else { job = job.toLowerCase() }
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){ if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" } else { GEN.checkInout({job:job,mode:"out"}) } }
	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}

	var ret = IKM.crud('selectArrayMap', {
        table: "pdm_job_imp",
        field: ["signal1","org_line_width1","org_spacing","line_width1"],
        where: {job_id:JobId}
	})
    var info = {}
    var layerCount = IKM.get_jobinfo({jobid: JobId,jobinfo:"layer_count"}) || GEN.getLayerCount({job:job})
    ret.forEach(function(row) {
        if(row.line_width1 != row.org_line_width1){
            var layer = getRow(row.signal1,layerCount) 
            if(!info[layer]) { info[layer] = {} }
            if(!info[layer][row.org_line_width1]) { info[layer][row.org_line_width1] = {} }
            if(row.org_spacing) {
                info[layer][row.org_line_width1][row.org_spacing] = row.line_width1
            } else {
                info[layer][row.org_line_width1].other = row.line_width1
            }
        }
    })
    var matrix = GEN.getMatrix({job:job})
    var work_layers = Object.keys(matrix).filter(function(v){
		var info = matrix[v];
		var reg;
		if(par.workLayer == "inner") {
			reg = /inner/
		} else if (par.workLayer == "out") {
			reg = /top|box/
		} else {
			reg = /inner|top|box/
		}
        return info.context == "board" && info.layer_type == "signal" && reg.test(info.side)
	})
    stepList.forEach(function(step){
        GEN.openStep({ job: job, name: step });
        GEN.clearLayers(); //清除层显示
        GEN.affectedLayer({ mode: 'all', affected: 'no' }); //设置影响层全部不影响
        GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
        GEN.units({ type: par.units }); //单位初始化
        GEN.zoomHome(); //窗口显示回到原始位置
        GEN.selClearFeature()
		
		for (var layer in info) {
			if(work_layers.indexOf(layer) >= 0) {
				var change = info[layer]
				var tmp = layer + "_tmp";
				if(GEN.isLayerExists({job:job, layer:tmp})) {GEN.deleteLayer({job:job, layer:[tmp]})}
				GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
				GEN.selectByFilter({feat_types:"line"})
				if(GEN.getSelectCount() > 0) {
					GEN.selMoveOther({target_layer:tmp,invert:'no',dx:0,dy:0,size:0})
					for (var width in change) {
						var space = change[width];
						// gtl:{"106.7":{"121.9":101.6},"190.5":{"other":177.8}},
						var samesym = GEN.getLayerSymsHist({job:job,step:step,layer:tmp,units:'mm'})
						samesym = Object.keys(samesym).filter(function(v){return Math.abs(Number(v.slice(1)) - width) <= 1})
						for (var key in space) {
							if(key !== "other") {
								GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'})
								GEN.selectByFilter({include_syms:samesym.join(";")})
								if(GEN.getSelectCount() > 0) {
									// 拷贝到辅助层 将|线距-key<1 的selChangeSym space[key]
									if(GEN.isLayerExists({job:job,layer:tmp + "2"})){
										GEN.deleteLayer({job:job, layer:tmp + "2"})
									}
									GEN.selMoveOther({target_layer:tmp + "2",invert:'no',dx:0,dy:0,size:0})
									GEN.workLayer({name:tmp + "2",display_number:2,clear_before:'yes'})
									// 创建chklist并运行
									var ck = "space_analysis"
									if(GEN.isChklistExists({job:job,step:step,chklist:ck})){
										GEN.COM("chklist_delete,chklist=" + ck)
									}
									GEN.COM("chklist_create,chklist=" + ck)
									GEN.COM("chklist_show,chklist=" + ck)
									GEN.COM("chklist_pclear")
									GEN.COM("chklist_single,action=valor_analysis_signal,show=yes")
									GEN.COM("chklist_cupd,chklist=valor_analysis_signal,nact=1,params=((pp_layer="+tmp + "2"+")(pp_spacing=203)(pp_r2c=381)(pp_d2c=356)(pp_sliver=254)(pp_min_pad_overlap=127)(pp_tests=Spacing)(pp_selected=All)(pp_check_missing_pads_for_drills=No)(pp_use_compensated_rout=No)(pp_sm_spacing=No)),mode=regular")
									GEN.COM("chklist_pcopy,chklist=valor_analysis_signal,nact=1")
									GEN.COM("chklist_ppaste,chklist="+ck+",row=0")
									GEN.COM("chklist_close,chklist=valor_analysis_signal,mode=hide")
									GEN.COM("chklist_cupd,chklist="+ck+",nact=1,params=((pp_layer="+tmp + "2"+")(pp_spacing=203)(pp_r2c=381)(pp_d2c=356)(pp_sliver=254)(pp_min_pad_overlap=127)(pp_tests=Spacing)(pp_selected=All)(pp_check_missing_pads_for_drills=No)(pp_use_compensated_rout=No)(pp_sm_spacing=No)),mode=regular")
									GEN.COM("chklist_run,chklist="+ck+",nact=1,area=profile")
									// 获取info信息 计算c2c 距离转um - key < 1的 点选
									var cshfile = GEN.INFO({
										units: "mm", 
										entity_type: 'check',
										entity_path: job + "/" + step + "/" + ck,
										data_type: 'MEAS',
										options: "action=1+category=c2c+layer=" + tmp + "2",
										parse:'no'
									});
									var lines = fs.readFile(cshfile).split(/\r?\n/);
									fs.unlink(cshfile);
									// "c2c l3_tmp2 101.53 micron r101.6 r101.6 SG 59.9799225 117.9374275 60.051715 117.8656325 1 R",
									lines = lines.filter(function(v) {
										var tmp_mean = v.split(" ")
										return tmp_mean[2] - key < 1
									})
	
									lines.forEach(function(v) {
										var tmp_mean = v.split(" ")
										var x1 = tmp_mean[7]
										var y1 = tmp_mean[8]
										var x2 = tmp_mean[9]
										var y2 = tmp_mean[10]
										GEN.COM("sel_net_feat,operation=select,x="+x1+",y="+y1+",use_ffilter=no")
										GEN.COM("sel_net_feat,operation=select,x="+x2+",y="+y2+",use_ffilter=no")
									})
									// 将选中的线changeSym   space[key]
									if(GEN.getSelectCount() > 0) {
										GEN.selChangeSym({symbol:"r" + space[key]})
									}
	
									// 将本层移动回去
									GEN.selMoveOther({target_layer:tmp,invert:'no',dx:0,dy:0,size:0})
									GEN.deleteLayer({job:job, layer:tmp + "2"})
								}
							}
						}
						if(space.other) {
							// r101.*;r101
							GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'})
							GEN.selectByFilter({include_syms:samesym.join(";")})
							if(GEN.getSelectCount() > 0) {
								GEN.selChangeSym({symbol:"r" + space.other})
							}
						}
					}
					GEN.workLayer({name:tmp,display_number:2,clear_before:'yes'})
					GEN.selMoveOther({target_layer:layer,invert:'no',dx:0,dy:0,size:0})
					if(GEN.isLayerExists({job:job, layer:tmp})) {GEN.deleteLayer({job:job, layer:[tmp]})}
				}
			}
		}
    })


	// 保存 
	if(/yes/ig.test(par.auto_save)){GEN.checkInout({job:job,mode:"out"}); GEN.saveJob({ job: job });GEN.checkInout({job:job,mode:"in"});GEN.closeJob({job:job});} else {GEN.checkInout({job:job,mode:"in"})}
	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) { Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else { resultData.push({ type: "info", title: "操作完成, 请注意检查!" }); return {status: Status,result_data: resultData}; }
	}else { return "Done" }
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"));IKM.msg(e);Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function getRow( signal1, layerCount) {
    if (signal1 == 1) {
        return "gtl"
    } else if (signal1 == layerCount) {
        return "gbl"
    } else {
        return "l" + signal1
    }
}




var tmp2 = {
	"gtl": {
		"127": { "177.8": 129.54 },
		"215.9": { "other": 220.98 }
	},
	"gbl": {
		"127": { "177.8": 129.54 },
		"215.9": { "other": 220.98 }
	},
	"l3": {
		"127": { "other": 132.08 }
	},
	"l5": { "127": { "other": 132.08 } },
	"l8": {
		"127": { "other": 132.08 }
	},
	"l10": {
		"127": { "other": 132.08 }
	}
}